import Toast from '@vant/weapp/toast/toast';
import utils from '../../utils/formatTimestamp'
const {
    wxml,
    style
} = require('./ProductDemo.js')
const APP = getApp()
Page({
    imagePath: '',
    history: [],
    future: [],
    isSave: false,

    /**
     * 页面的初始数据
     */
    data: {
        src: "",
        id: null,
        fxshow: false,
        s_id: null,
        pageLoading: false,
        product: {},
        sildes: [],
        hotList: [],
        commit: [],
        showOverlay: false,
        dots: false,
        resourceURL: '',
        shop: {},
        p_s_name: '请选择',
        shop_id: '',
        stock: [],
        show: false,
        value: 1,
        arr: null,
        idx: 0,
        is_coll: 1,
        codePath: '',
        scene: '',
        template: {},
        customActionStyle: {
            border: {
                borderColor: '#1A7AF8',
            },
            scale: {
                textIcon: '/palette/switch.png',
                imageIcon: '/palette/scale.png',
            },
            delete: {
                icon: '/palette/close.png',
            },
        },
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let id = null
        if (options.scene) {
            id = APP.globalData.getQueryVariable(decodeURIComponent(options.scene)).id
        }
        this.setData({
            id: id || options.id,
            s_id: options.s_id,
            resourceURL: `${wx.api.host}/`,
        })

    },



    // 规格选中
    onActive(e) {
        this.setData({
            idx: e.currentTarget.dataset.index,
            p_s_name: this.data.stock[e.currentTarget.dataset.index].p_s_name
        })
    },
    // 数量
    onChange(event) {
        this.setData({
            value: event.detail
        })
    },
    // 显示购物车
    showPopup() {
        this.setData({
            show: true
        });
    },
    // 加入购物车
    joinCart(e) {
        // console.log(e);
        let status = e.currentTarget.dataset.id
        // console.log(status);
        wx.http.post(wx.api.usereditcart, {
            quantity: this.data.value,
            stock_id: this.data.stock[this.data.idx].p_s_id,
            product_id: this.data.id
        }).then(res => {
            if (res.code != 1) {
                return true
            }

            if (status == 1) {
                wx.showToast({
                    title: '已加入购物车',
                    icon: 'success'
                })
                this.setData({
                    show: false,
                    value: 1,

                })
            } else {
                var cardid = res.data
                wx.navigateTo({
                    url: '/pages/settlement/index?cart_ids=' + cardid,
                })
                // console.log(cardid);
            }
        })
    },
    onClose() {
        this.setData({
            show: false,
            value: 1
        });
    },
    // 获取商品详情
    getProductDetail() {
        wx.http.post(wx.api.productinfo, {
            product_id: this.data.id,
        }).then(res => {
            if (res.code === 1) {
                this.setData({
                    product: res.data.product,
                    sildes: [res.data.product.imageurl],
                    pageLoading: true,
                    shop: res.data.shop,
                    stock: res.data.stock,
                    shop_id: res.data.shop.shop_id,
                    is_coll: res.data.is_coll
                })
                wx.setNavigationBarTitle({
                    title: this.data.product.product_name,
                })
                // Toast.clear()
                this.getHotProduct()
                this.getProductCommit()
            }
        })
    },
    // 收藏
    collect(e) {
        let id = e.currentTarget.dataset.id
        let that = this
        wx.http.post(wx.api.collectproduct, {
            product_id: id
        }).then(res => {
            if (this.data.is_coll == 1) {
                Toast({
                    type: 'success',
                    message: '收藏成功',
                    onClose: () => {
                        this.getProductDetail()
                    },
                });
            } else {
                Toast({
                    type: 'success',
                    message: '取消收藏',
                    onClose: () => {
                        this.getProductDetail()
                    },
                });
            }
            // if (res.code == 1) {
            //  console.log(2);

            // } else {
            //     console.log(3);
            //     
            // }


        })
    },
    // 热门商品列表
    getHotProduct(e) {
        wx.http.get(wx.api.gethotproduct, {
            shop_id: this.data.shop_id
        }).then(res => {
            // console.log(res);
            // if (res.code === 1) {
            //     // let _hotList = res.data.data.filter((item) => {
            //     //     return item.product_id != e.product_id
            //     // })

            // }
            this.setData({
                hotList: res.data.data
            })
        })
    },

    // 获取商品评价
    getProductCommit() {
        wx.http.get(wx.api.getproductcommit, {
            product_id: this.data.product.product_id,
            type: 1,
        }).then(res => {
            if (res.code === 1) {
                this.setData({
                    // commit:res.data.data
                    commit: res.data.data.map(e => {
                        return {
                            ...e,
                            time: utils.formatTimestamp(e.add_time),
                            avatar: !e.avatar.startsWith('http') ? this.data.resourceURL + e.avatar : e.avatar,
                            imgarr: e.images.slice(0, 3)
                        }
                    })
                })
                // console.log(this.data.commit[0].imgarr);
            }
            // console.log(this.data.commit)
        })
    },

    //图片预览
    previewImages(obj) {
        let e = obj.currentTarget.dataset.e
        let arr = []
        for (let index = 0; index < e.length; index++) {
            let element = this.data.resourceURL + e[index];
            arr.push(element)
        }
        wx.previewImage({
            urls: arr,
            current: obj.currentTarget.dataset.curr
        })
    },

    // 推荐商品
    productTo(obj) {
        // console.log(obj);
        let e = obj.currentTarget.dataset.e
        wx.navigateTo({
            url: `/packageA/ProductDetails/index?id=${e.product_id}`,
        })
    },

    // 评价列表 or 店铺主页
    pageTo(obj) {
        let e = obj.currentTarget.dataset
        // console.log(obj.currentTarget.dataset);
        wx.navigateTo({
            url: `${e.url}?id=${e.id}&&type=1&&shop_id=${e.id}`,
        })
    },

    // 立即兑换
    // exchangeGoods() {
    //     let uinfo = JSON.parse(wx.getStorageSync('uinfo'))
    //     if (parseFloat(uinfo.growth_coin) >= parseFloat(this.data.product.integral)) {
    //         Toast.loading('加载中')
    //         setTimeout(() => {
    //             wx.navigateTo({
    //                 url: `/packageC/settlement/index?id=${this.data.product.product_id}&s_id=${this.data.product.p_s_id}`,
    //             })
    //             Toast.clear()
    //         }, 1000);
    //     } else {
    //         Toast.fail('积分不足')
    //     }
    // },




    // 分享提示

    tipShare() {
        wx.showLoading({
            title: '海报生成中',
        })
        let {
            product,
            shop,
            codePath
        } = this.data
        this.setData({

            paintPallette: {
                width: '588rpx',
                height: '900rpx',
                background: '#FFFFFF',
                views: [{
                        type: "image",
                        url: `${wx.api.host}/${product.imageurl}`,
                        css: {
                            width: "588rpx",
                            height: "588rpx",
                            mode: "aspectFill",
                            right: "0rpx",
                            top: "0rpx",
                            borderRadius: "0 0 106rpx  106rpx"
                        },
                    },
                    {
                        type: "image",
                        url: codePath,
                        css: {
                            width: "168rpx",
                            height: "168rpx",
                            mode: "aspectFill",
                            right: "24rpx",
                            bottom: "243rpx",
                            borderRadius: "50%"
                        },
                    },
                    {
                        type: "text",
                        text: "￥",
                        css: {
                            left: "24rpx",
                            bottom: "234rpx",
                            fontSize: "24rpx",
                            color: "#F33224",
                            fontWeight: "bold"
                        },
                    },
                    {
                        type: "text",
                        text: product.mprice,
                        css: {
                            left: "49rpx",
                            bottom: "234rpx",
                            fontSize: "40rpx",
                            color: "#F33224",
                            fontWeight: "bold"
                        },
                    },
                    {
                        type: "text",
                        text: product.product_name,
                        css: {
                            left: "24rpx",
                            bottom: "192rpx",
                            fontSize: "32rpx",
                            color: "#202327",
                            fontWeight: "bold"
                        },
                    },
                    {
                        id: 'one',
                        type: 'rect',
                        css: {
                            width: '540rpx',
                            height: '88rpx',
                            left: '24rpx',
                            bottom: '80rpx',
                            color: "#FF7733",
                            borderRadius: "44rpx"
                        },
                    },
                    {
                        type: "text",
                        text: "点击保存照片 扫码下单",
                        css: {
                            left: "172rpx",
                            bottom: "110rpx",
                            fontSize: "28rpx",
                            color: "#FFFFFF",
                        },
                    },
                    {
                        type: "image",
                        url: "../../static/wx.png",
                        css: {
                            width: "42rpx",
                            height: "34rpx",
                            mode: "aspectFill",
                            left: "124rpx",
                            bottom: "106rpx",
                        },
                    },
                    {
                        type: "image",
                        url: `${wx.api.host}/${shop.imagesurl}`,
                        css: {
                            width: "34rpx",
                            height: "34rpx",
                            mode: "aspectFill",
                            left: "24rpx",
                            bottom: "24rpx",

                        },
                    },
                    {
                        type: "text",
                        text: shop.shop_name,
                        css: {
                            left: "70rpx",
                            bottom: "30rpx",
                            fontSize: "24rpx",
                            color: "#06021A",
                        },
                    },

                ],
            },

        })
        setTimeout(() => {
            wx.hideLoading()
            this.setData({
                fxshow: true,
            })
        }, 1500);

    },

    onCloseShare() {
        this.setData({
            fxshow: false
        });
    },

    onShare() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
            success: function (res) {
                console.log(res);
                wx.showToast({
                  title: `成功${res}`,
                })
            },
            fail: function (res) {
                console.log("fail",res);
                wx.showToast({
                    title: res,
                  })
            },
        })
        console.log(1);
    },
    onImgOK(e) {
        this.imagePath = e.detail.path;
        this.setData({
            image: this.imagePath,
        });
        if (this.isSave) {
            this.saveImage(this.imagePath);
        }
    },


    saveImage() {

        if (this.imagePath && typeof this.imagePath === 'string') {
            this.isSave = false;
            wx.authorize({
                scope: 'scope.writePhotosAlbum',
            }).then(res => {
                console.log(this.imagePath);
                return wx.saveImageToPhotosAlbum({
                    filePath: this.imagePath,
                })
            }).then(res => {
                console.log(res);
                wx.showToast({
                    title: '保存成功',
                })
            }).catch(err => {
                console.error(err);
                wx.openSetting()
                wx.showToast({
                    title: '保存失败',
                })
            });
        }
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

        wx.http.post(wx.api.GetNormalQrCode, {
            url: `packageA/ProductDetails/index?id=${this.data.id}`
        }).then(res => {
            const path = `${wx.api.host}/${res.data.path}`
            console.log(path);
            this.setData({
                codePath: path
            })

        })

        this.getProductDetail(this.data.id)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: this.data.product.product_name,
            path: `packageA/ProductDetails/index?id=${this.data.id}`,
            imageUrl: this.data.resourceURL + this.data.product.imageurl,
        }
    }
})